﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
namespace HNRoadFormatConverter.Commons
{
    public class ExcelHelperNpoi
    { 
        public static void WriteDataTableToExcel(DataTable dataTable, string filePath, string SheetName = "Sheet1")
        {
            // 创建Excel工作簿
            IWorkbook workbook = new XSSFWorkbook();

            // 创建工作表
            ISheet sheet = workbook.CreateSheet(SheetName);

            // 创建表头行
            IRow headerRow = sheet.CreateRow(0);

            // 写入表头
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                headerRow.CreateCell(i).SetCellValue(dataTable.Columns[i].ColumnName);
            }

            // 写入数据
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                IRow dataRow = sheet.CreateRow(i + 1);
                for (int j = 0; j < dataTable.Columns.Count; j++)
                {
                    dataRow.CreateCell(j).SetCellValue(dataTable.Rows[i][j].ToString());
                }
            }

            // 保存文件
            using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                workbook.Write(fs);
            }
        }
    }
}
